#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动完整的AI虚拟主播系统
包括 HTTP 服务器、WebSocket 服务器和主程序
"""

import subprocess
import time
import sys
import webbrowser
from pathlib import Path

def start_http_server():
    """启动 HTTP 服务器"""
    print("正在启动 HTTP 服务器...")
    server_script = Path(__file__).parent / "start_live2d_server.py"
    
    # 启动 HTTP 服务器（后台运行）
    process = subprocess.Popen(
        [sys.executable, str(server_script)],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        creationflags=subprocess.CREATE_NEW_CONSOLE if sys.platform == 'win32' else 0
    )
    
    print(f"✓ HTTP 服务器已启动 (PID: {process.pid})")
    print("  地址: http://localhost:8000")
    
    return process

def start_main_program():
    """启动主程序"""
    print("\n正在启动主程序...")
    main_script = Path(__file__).parent / "main.py"
    
    # 启动主程序（前台运行）
    process = subprocess.Popen(
        [sys.executable, str(main_script)],
        creationflags=subprocess.CREATE_NEW_CONSOLE if sys.platform == 'win32' else 0
    )
    
    print(f"✓ 主程序已启动 (PID: {process.pid})")
    
    return process

def main():
    print("=" * 70)
    print("AI 虚拟主播系统启动器")
    print("=" * 70)
    
    processes = []
    
    try:
        # 1. 启动 HTTP 服务器
        http_server = start_http_server()
        processes.append(http_server)
        time.sleep(2)  # 等待服务器启动
        
        # 2. 打开浏览器
        print("\n正在打开 Live2D 渲染页面...")
        webbrowser.open("http://localhost:8000/web_live2d_complete.html")
        print("✓ 浏览器已打开")
        time.sleep(1)
        
        # 3. 启动主程序
        main_program = start_main_program()
        processes.append(main_program)
        
        print("\n" + "=" * 70)
        print("系统启动完成!")
        print("=" * 70)
        print("\n使用说明:")
        print("1. Live2D 页面会自动在浏览器中打开")
        print("2. 主程序正在另一个控制台窗口中运行")
        print("3. 关闭此窗口会停止所有进程")
        print("\n按 Ctrl+C 停止所有服务...")
        
        # 等待用户中断
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n\n正在停止所有服务...")
            
    except Exception as e:
        print(f"\n启动失败: {e}")
        
    finally:
        # 清理所有进程
        for process in processes:
            try:
                process.terminate()
                process.wait(timeout=5)
                print(f"✓ 进程 {process.pid} 已停止")
            except Exception as e:
                print(f"停止进程 {process.pid} 失败: {e}")
        
        print("\n所有服务已停止")

if __name__ == '__main__':
    main()
